#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import requests
from scrapy.utils.project import get_project_settings


class JuHeVerifyCode(object):
    """
    聚合验证码识别：
    1、验证码类型查询 http://op.juhe.cn/vercode/codeType
    """
    def __init__(self):
        settings = get_project_settings()
        self.app_key = settings.get('JUHE_APPKEY', '5a9149bedf65cb06774a87a83ecddb39')
        self.url = 'http://op.juhe.cn/vercode/index'

    # 识别验证码
    def verify(self, image, code_type='1005'):
        img_file = {'image': ('image', open(image, 'rb'), 'image/png', {'Expires': '0'})}
        params = {
            'key': self.app_key,
            'codeType': code_type,
            'dtype': 'json',  # 返回的数据的格式，json或xml，默认为json
        }
        r = requests.post(self.url, params, files=img_file)
        res = json.loads(r.content)
        if res:
            error_code = res['error_code']
            if error_code == 0:
                # 成功请求
                code = res['result']
                print(code)
                return code
            else:
                print('%s:%s' % (res['error_code'], res['reason']))
        else:
            print('request api error')


if __name__ == '__main__':
    # 1.识别验证码
    JuHeVerifyCode().verify('/work/cmcc/verify_code/111.png')